﻿using System;
using System.Collections.Generic;
using System.Linq;
using Ewk.MachineLearning.Persistance.Interfaces;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Rhino.Mocks;

namespace Ewk.MachineLearning.Persistance.DataAccess.UnitTests
{
    [TestClass]
    public class GetOrCreateEntityTests : RepositoryTestBase
    {
        [TestMethod]
        public void When_GetOrCreateEntity_is_called_with_a_string_that_is_not_present_Then_Catalog_Save_is_called()
        {
            var content = Guid.NewGuid().ToString();
            var entities = new List<TestTextEntity>();
            var entity = new TestTextEntity { Content = content };

            var catalog = MockRepository.GenerateMock<ICatalog>();

            catalog
                .Expect(c => c.Entities<TestTextEntity>())
                .Return(entities.AsQueryable())
                .Repeat.Once();
            catalog
                .Expect(c => c.Add(
                    Arg<TestTextEntity>.Matches(textEntity =>
                                                textEntity.Content == content.ToUpperInvariant())))
                .Return(entity)
                .Repeat.Once();
            catalog.Replay();

            var repository = new TextEntityRepository<TestTextEntity>(catalog);
            repository.GetOrCreateEntity(content);

            catalog.VerifyAllExpectations();
        }

        [TestMethod]
        public void When_GetOrCreateEntity_is_called_with_a_string_that_is_already_present_Then_Catalog_Save_is_not_called()
        {
            var content = Guid.NewGuid().ToString().ToUpperInvariant();
            var entity = new TestTextEntity { Content = content };
            var entities = new List<TestTextEntity> { entity };

            var catalog = MockRepository.GenerateMock<ICatalog>();

            catalog
                .Expect(c => c.Entities<TestTextEntity>())
                .Return(entities.AsQueryable())
                .Repeat.Once();
            catalog
                .Expect(c => c.Add(
                    Arg<TestTextEntity>.Matches(textEntity =>
                                                textEntity.Content == content)))
                .Return(entity)
                .Repeat.Never();
            catalog
                .Expect(c => c.Update(entity))
                .Repeat.Never();
            catalog.Replay();

            var repository = new TextEntityRepository<TestTextEntity>(catalog);
            repository.GetOrCreateEntity(content);

            catalog.VerifyAllExpectations();
        }
    }
}